<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 14-5-12
 * Time: 下午10:33
 */
namespace builder\console\controllers;

use Ulue;
use builder\console\parts\ConsoleController;
use ulue\cli\CliInteract;

class ModuleController extends ConsoleController
{

    protected $parentClass = 'ulue\web\Module';

    public function indexCommand($name='', $path=null, $tpl=null)
    {
        if ($this->io->getOption('help') || $this->io->getArguments('h')) {
            $this->helpCommand();

            return;
        }

        if (!$path) {
            $path       = $this->rootPath;
        }

        $this->path = $path;

        if ($tpl) {
            $this->tpl = $tpl;
        }

d(
    $this->io->getArguments(),
    $this->io->getOptions(),
    $name
    );

        if (!$name) {
            $name = CliInteract::loopAsk('please entry module name:');
        }

        $modulePath = "$path/src/$name";

        CliInteract::panel([
            'moduleName'   => $name,
            'modulePath'   => $modulePath,
            'templateName' => $this->tpl,
            'templatePath' => Ulue::$app->module->path . '/tpls/' . $this->tpl,
            ]);

        if ( ! CliInteract::confirm('Will be ready to create the ['.$name.'] module dir struct') )
        {
            CliInteract::out(' Quit create.', 1);
        }

        if ( !$this->io->input->exists('force') &&
         is_dir($modulePath) && !CliInteract::confirm("module dir $modulePath exist! Still create?")
         ) {
            CliInteract::out(' Quit2 .', 1);
        }

        $framework  = $this->rootPath.'/vendor/uluefk/framework';
        $moduleTplFile  = $path.'/building/tpl/module.tpl';
        $moduleDirConfig = Ulue::$app->module->moduleDirConfig;
        $dirSetting = require( Ulue::resolveAlias($moduleDirConfig) );

        // 创建一个模块

        CliInteract::out("Start create module dir...\n\n");

        foreach ((array)$dirSetting as $dir) {
            $dir = "$modulePath/$dir";

            if (!is_dir($dir)) {
                echo "      Create dir $dir\n";
                make($dir);
            }else {
                echo "      Skip create $dir , is exist.\n";
            }
        }

        $content = file_get_contents($moduleTplFile);
        $moduleClass = ucfirst($name) . 'Module';
        $moduleFile = $modulePath . '/' . $moduleClass . '.php';
        $content = strtr($content, [
                '{moduleName}'      => $name,
                '{moduleClassName}' => $moduleClass
            ]);

        echo "\n    create module entry file: {$moduleClass}.php\n";

        if (file_exists($moduleFile)) {
            echo "\n    Skip create entry file: {$moduleClass}.php , exist.\n";
        } else {
            file_put_contents($moduleFile, $content);
        }

        CliInteract::out("... module [$name] create completed!\n\n");
    }

    public function helpCommand()
    {
        echo 'ddddddddddddddddddd';
    }
}